//
//  status.swift
//  MicroBlog
//
//  Created by QT on 15/8/2.
//  Copyright © 2015年 綦敦涛. All rights reserved.
//

import UIKit
import  SDWebImage
class status: NSObject {

    // 微博创建时间
    var created_at: String?
    // 微博ID
    var id: Int = 0
    // 微博信息内容
    var text: String?
    // 微博来源
    var source: String?
    // 微博行高
    var rowheigh: CGFloat?
    // 转发微博
    var retweeted_status: status?
    // 配图数组
    var pic_urls: [[String: AnyObject]]?
        {
        didSet{
            if pic_urls?.count == 0{
                return
            }
            currentPic_URL = [NSURL]()
            large_URL = [NSURL]()
            for dict in pic_urls!{
                // 缩略图
                if let urlString = dict["thumbnail_pic"] as? String{
                    currentPic_URL?.append(NSURL(string: urlString)!)
                    // 添加大图
                    let largePic_URLStr = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
            
                    large_URL?.append(NSURL(string: largePic_URLStr)!)
                }
            }
        }
    }
    // 自己的微博配图URL数组
    private var currentPic_URL: [NSURL]?
    // 转发微博的URL配图数组，pic_URL “计算型”属性
    var pic_URL: [NSURL]?{
        return retweeted_status == nil ? currentPic_URL : retweeted_status?.currentPic_URL
    }
    
    // 大图
    private var large_URL: [NSURL]?
    // 
    var largePic_URL: [NSURL]?{
        return retweeted_status == nil ? large_URL : retweeted_status?.large_URL
    }
    
    
    // 用户
    var User: user?
    
    
    // MARK: -加载微博数据
    class func loadStatus(since_id: Int,max_id: Int,finished:(datalist: [status]?,error: NSError?)->()){
        
        
        NetWorkTools.sharedTools.loadStatuses(since_id,max_id: max_id) { (result, error) -> () in
            if error != nil{
                finished(datalist: nil, error: error)
                return
            }
            
            // 网络请求获得的字典数组
            
            if let array = result?["statuses"] as? [[String: AnyObject]]{
                var datalist = [status]()
                for stat in array{
                    
                    // 字典转模型，并且存入数组
                    datalist.append(status(dict: stat))
                }
                
                
                // 缓存图片到本地
                status.cacheWebImg(datalist,finished: finished)
                

                
            }else{
                finished(datalist: nil, error: nil)
            }
            
            
        }
    }
    
    
    // 缓存图片
    class private func cacheWebImg(list:[status],finished:(datalist: [status]?,error: NSError?)->()){
        
        let groud = dispatch_group_create()
        for stat in list{
            guard let a = stat.pic_URL else{
                continue
            }
            for url in a{
                dispatch_group_enter(groud)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 1), progress: nil, completed: { (image, _, _, _, _) -> Void in
                dispatch_group_leave(groud)
                })
            }
        }
        dispatch_group_notify(groud, dispatch_get_main_queue()) { () -> Void in
            print("缓存完成")
            finished(datalist: list, error: nil)
            
        }
    }
    
    
    // MARK: - 构造方法
    init(dict: [String: AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user"{
            if let dict = value as? [String: AnyObject]{
                User = user(dict: dict)
            }
            return 
            
        }
        if key == "retweeted_status"{
            if let dict = value as? [String: AnyObject]{
               retweeted_status = status(dict: dict)
            }
            return 
        }
        super.setValue(value, forKey: key)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {    }
}
